package com.crm.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.utils.ThreadLocalUtil;
import com.crm.entity.Clue;
import com.crm.entity.ClueFollow;
import com.crm.service.ClueFollowService;
import com.crm.mapper.ClueFollowMapper;
import com.crm.service.ClueService;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
* @author chy
* @description 针对表【clue_follow(线索跟进表)】的数据库操作Service实现
* @createDate 2025-09-04 20:46:14
*/
@Service
@Slf4j
public class ClueFollowServiceImpl extends ServiceImpl<ClueFollowMapper, ClueFollow> implements ClueFollowService{


    @Autowired
    private ClueService clueService;
    /**
     * 根据线索id查询跟进记录
     * @param clueId
     * @return
     */
    @Override
    public List<ClueFollow> listByClueId(Long clueId) {

        if(clueId == null){
            return null;
        }
        List<ClueFollow> list = list(new LambdaQueryWrapper<ClueFollow>()
                .eq(ClueFollow::getClueId, clueId)
                .orderByDesc(ClueFollow::getCreateTime));
        log.info("查询线索跟进：{}", list);
        return list;
    }

    /**
     * 保存线索的跟进记录
     * @param clueFollow
     */
    @Override
    @Transactional
    public void saveClueFollow(ClueFollow clueFollow) {

        super.save(clueFollow);

        LocalDateTime nextTime = clueFollow.getNextTime();
        // 判断条件并更新线索表中的下次联系时间
        Long clueId = clueFollow.getClueId();

        //同步更新到clue表
        if(nextTime != null && clueId != null){
            clueService.update(new LambdaUpdateWrapper<Clue>()
                    .eq(Clue::getId, clueId)
                    .set(Clue::getNextTime, nextTime));
        }
    }
}




